<?php

namespace app\api\controller;
use data\Json;
use think\Request;
use think\Cache;
use think\Validate;
use app\common\model\Activity;
use app\admin\model\Feedback;
use app\admin\model\Chat;
use JPush\Client as JPush;
/**
 * 社群/用户 注册+登录+发送短信验证码
 */
class Index extends Base
{
    protected $user_model = null;
    protected $token = null;

    public function _initialize()
    {
        $this->user_model = model('User');
        $this->token = request()->header('token');
        $this->user_model = $this->user_model->getUserInfo($this->token);
        //$this->user = $this->user_model->get('30');
    }

    public function test()
    {
       $this->assign('res', 'https://v.qq.com/x/page/n0397v0xidp.html');
       return $this->fetch();
    }

    // 发送短信验证码
    public function sms()
    {
        $validate = new Validate([
            ['mobile','require|/1[34578]{1}\d{9}$/','联系方式不能为空|手机号码格式错误'],
        ]);

        $mobile = $data['mobile'] = input("mobile");
        if (!$validate->check($data)) return Json::array_send(1,$validate->getError());
        return $this->sendSMS($mobile);
    }

    // 验证短信验证码
    public function verifyCode(Request $request)
    {
        if($request->isPost())
        { 
            $validate = new Validate([
                ['mobile','require|/1[34578]{1}\d{9}$/','联系方式不能为空|手机号码格式错误'],
                ['code','require','手机验证码不能为空'],
            ]);
            $data = input();
            $mobile = $data['mobile'] = input("mobile");
            if (!$validate->check($data)) return Json::json_send(1,$validate->getError());
            if($data['code']==Cache::get($mobile))
            {
                return Json::json_send(0);
            }
            return Json::json_send(403);
        }
        return Json::json_send(4);
    }

    // 用户、社群登录
    public function login(Request $request)
    {
        if($request->isPost())
        { 
            $data = input();
            $vali = $this->validate($data,'User.validate');
            if($vali !== true) return Json::json_send($vali);
            $result=model('User')->login($data['mobile'],$data['code']);
            if(!$result){
                return Json::json_send(2);
            }
            if($result['state'] == 0){
                return Json::json_send(5);
            }
            else if($result['state'] == 2){
                return Json::json_send(6);
            }
            return Json::json_send(0,'',$result);
        }
        //return Json::json_send(4);
        return $this->view->fetch('index/login',['parentid'=>input('parentid',0),'communityid'=>input('communityid',0)]);// 活动商
    }

    // 用户、社群注册
    public function register(Request $request)
    {
        if($request->isPost()){
            $role = input('role');
            if(!$role)return Json::json_send(10005);
            $scenes = $role == 2?'User.member_register':'User.community_register';
            $data = input();
            $vali = $this->validate($data,$scenes);
            if($vali !== true) return Json::json_send($vali);
            return Json::json_send(model('User')->register($data));
        }
        
        //return Json::json_send(4);
        $community_id = input('communityid',0);
        $community = model('Community')->get($community_id);
        return $this->view->fetch('index/register',['parentid'=>input('parentid',0),'community'=>$community,'mobile'=>input('mobile',0)]);// 活动商
    }

        // 用户社群退出登录
    public function logout()
    {
        $user = $this->user_model->getUserInfo($this->token);
        if(!$user){return Json::json_send(1);}

        cache(config('tokenPrefix').$this->token, NULL);
        cache(config('tokenAndUserPrefix') . $user['id'], NULL);
        return Json::json_send(0,'退出成功');
    }
        // 供应商登录
    public function slogin(Request $request)
    {
        if($request->isPost())
        { 
            $data = input();
            $vali = $this->validate($data,'Supplier.validate');
            if($vali !== true) return Json::json_send($vali);
            $result=model('Supplier')->login($data['mobile'],$data['code']);
            if(!$result)
            {
                return Json::json_send(2);
            }
            if($result['state'] == 0)
            {
                return Json::json_send(5);
            }
            else if($result['state'] == 2)
            {
                return Json::json_send(6);
            }
            return Json::json_send(0,'',$result);
        }
        return Json::json_send(4);
    }

        // 供应商注册
    public function sregister(Request $request)
    {
        if($request->isPost())
        {
            $type = input('type');
            if(!$type)return Json::json_send(10005);
            $scenes = 'Supplier.site_reg';
            if($type == 2)
            {
                $scenes = 'Supplier.activity_reg';
            }
            else if($type == 3)
            {
                $scenes = 'Supplier.master_reg';
            }
            $data = input();
            $vali = $this->validate($data,$scenes);
            if($vali !== true) return Json::json_send($vali);
            return Json::json_send(model('Supplier')->register($data));
        }
        
        return Json::json_send(4);
    }

        // 供应商退出登录
    public function slogout()
    {
        $supplier = model('Supplier')->getUserInfo($this->token);
        if(!$supplier){return Json::json_send(1);}

        cache(config('tokenPrefix').$this->token, NULL);
        cache(config('tokenAndUserPrefix') . $supplier['id'], NULL);
        return Json::json_send(0,'退出成功');
    }

    // 发现
    public function blogs(Request $request)
    {
        if(!$this->user)return Json::json_send(1);
        if($request->isPost())
        {
            $data = input();
            $travel=model('travel')->get($data['travel_id']);
            $a_model = $travel['type']==1?model('Oversea'):model('Activity');
            $travel_activities = $a_model->alias('a')
                                    ->join('travel_activity ta','a.id=ta.activity_id')
                                    ->field('a.*,ta.begintime start,ta.endtime end')
                                    ->where(['ta.travel_id'=>$data['travel_id']])->select();
            $categorys = [];
            $titles = [];
            foreach ($travel_activities as $tk => $tv) {
                array_push($titles, $tv['name']);
            }
            $data['name'] = implode('+',$titles);
            if(model('blog')->allowField(true)->save($data))
            {
                $images = $this->multiUpload(request()->file('images'));
                $list = [];
                foreach ($images as $k => $v) {
                    $list[] = ['blog_id'=>model('blog')->id,'img'=>$v];
                }
                model('BlogPhotos')->saveAll($list);
                return Json::json_send(0);
            }
            return Json::json_send(9);
        }
        $blogs = model('blog')->select();
        $return = [];
        foreach ($blogs as $k => $v) {
            $zans = model('BlogZan')->get(['blog_id'=>$v['id']]);
            $comments = model('BlogComment')->get(['blog_id'=>$v['id']]);
            $return[]=[
                'id'   =>$v['id'],
                'name' =>$v['name'],
                'content' =>$v['content'],
                'zclick' =>count($zans),
                'commentNum' =>count($comments),
            ];
        }
        return Json::json_send(0,'',$return);
    }

    public function uploads()
    {
        if(request()->file('image'))
        {
            $files = request()->file('image');
            return Json::json_send(0,'',$this->multiUpload($files));
        }
        return Json::json_send(7);
    }
    
    public function cities()
    {
        $type = input('type',0);
        $data = model('city')->where('type',$type)->select();
        return Json::json_send(0,'',$data);
    }

    /**
     * 会员反馈
     * @return [type] [description]
     */
    public function feedback(Request $request)
    {
        $user_model = input('type')==2?model('User'):model('Supplier');
       // $user = $user_model->getUserInfo($this->token);
        $user = $user_model->get('2');
        if(!$user) return Json::json_send(1);
        if($request->isPost())
        {
            $data = input();
            $data['user_id'] = $user['id'];
            if(request()->file('img'))
            {
                $data['img'] = $this->upload(request()->file('img'));
            }
            $feedback_model = new Feedback();
            $result = $feedback_model->allowField(true)->save($data);

            if($result !== false) return Json::json_send(0);
            return Json::json_send(9);
        }

        $map['user_id'] = $user['id'];
        $map['type'] = input('type',2);

        $list = Feedback::where($map)->order('createtime desc')->select();
        return Json::json_send(0,'',$list);
    }

    /**
     * 会员获取聊天记录
     */
    public function hxchat(Request $request)
    {
       // $user = model('User')->getUserInfo($this->token);
        $user = model('User')->get('2');
        if(!$user) return Json::json_send(1);

        $chats = Chat::where('from', $user['hx_username'])->whereOr('to', $user['hx_username'])
                  ->order('timestamp asc')->select();

        if($chats)
        {
            foreach ($chats as $ck => $cv) 
            {
                $chats[$ck]['payload'] = json_decode($cv['payload'],true);
            }
        } 

        return Json::json_send(0,'',$chats);
    }
}
